package com.morntea.photospider;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.morntea.photospider.WebHunter.*;

public class PhotoSpider {
	public static void main(String[] args) {
		if(args.length>=1){
			downPhoto(args[0], null);
		}
		//downPhoto("http://www.wretch.cc/album/show.php?i=ghq357&b=30&f=1155471945&p=0",null);		
	}
	public static void downPhoto(String firstPageUrl, String savePath) {
		if(firstPageUrl==null)return;
		
		String nextPage = firstPageUrl;		
		PhotoFactory photoCamera = PhotoFactory.createCamera(nextPage);
		if(savePath==null || savePath.equals("")){
			savePath = photoCamera.savePath;
		}
		
		Pattern nextPagePattern = Pattern.compile(photoCamera.nextPageRegex, Pattern.DOTALL);
		Pattern picPattern = Pattern.compile(photoCamera.imageRegex, Pattern.DOTALL);
		
		int count = 0;
		String picUrl="", picName="", lastName="";
		while(nextPage!=null){
			count++ ;
			String webContent = getWebAsString(photoCamera.getNextPhotoUrl(nextPage), "big5");
			//System.out.println(webContent);
			
			/* Get picture */
			Matcher picMatcher = picPattern.matcher(webContent);
			if(picMatcher.find()){
				//System.out.println(picMatcher.group());
				picUrl = photoCamera.getImageUrl(picMatcher.group(1));
				picName = picMatcher.group(2);
				
				if(picName.equals(lastName)){
					System.out.println("Finish downloading.");
					return;
				}else{
					lastName = picName;
				}
				
				savePageToFile(picUrl, savePath+picName);
				System.out.println(count+":"+picUrl);
			}else{
				picUrl = "";
				picName = "";
				System.out.println(count + ":" + "Can't parse out picture in "+nextPage);
			}

			/* Get next page url */
			Matcher nextPageMatcher = nextPagePattern.matcher(webContent);
			if(nextPageMatcher.find()) {
				nextPage = nextPageMatcher.group(1);
			}else{
				System.out.println(count + ":Can't parse the next page url in " + nextPage + ". Maybe it's the last page.");
				nextPage = null;
			}
		}
	}
}
